<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="维修记录id" prop="maintenanceRecordsId">
        <el-input v-model="queryParams.maintenanceRecordsId" placeholder="请输入维修记录id" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车辆ID" prop="vehicleId">
        <el-input v-model="queryParams.vehicleId" placeholder="请输入车辆ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车牌号" prop="actualVehiclePlate">
        <el-input v-model="queryParams.actualVehiclePlate" placeholder="请输入车牌号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker v-model="daterangeStartTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="daterangeEndTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="维护用户ID" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入维护用户ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="维修用户姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入维修用户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="维护原因" prop="maintenanceReason">
        <el-input v-model="queryParams.maintenanceReason" placeholder="请输入维护原因" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="维护地点" prop="maintenanceLocation">
        <el-input v-model="queryParams.maintenanceLocation" placeholder="请输入维护地点" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="维护费用" prop="cost">
        <el-input v-model="queryParams.cost" placeholder="请输入维护费用" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['vehicles:records:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['vehicles:records:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['vehicles:records:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['vehicles:records:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="维修记录id" align="center" prop="maintenanceRecordsId" />
      <!-- <el-table-column label="车辆ID" align="center" prop="vehicleId" /> -->
      <el-table-column label="车牌号" align="center" prop="actualVehiclePlate" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="维护用户ID" align="center" prop="userId" /> -->
      <el-table-column label="维修用户姓名" align="center" prop="userName" />
      <el-table-column label="维护原因" align="center" prop="maintenanceReason" />
      <el-table-column label="维护地点" align="center" prop="maintenanceLocation" />
      <el-table-column label="维护费用" align="center" prop="cost" />
      <el-table-column label="维修发票" align="center" prop="invoice" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.invoice" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['vehicles:records:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['vehicles:records:remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改维护记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="车辆ID" prop="vehicleId">
          <el-input v-model="form.vehicleId" placeholder="请输入车辆ID" />
        </el-form-item>
        <el-form-item label="车牌号" prop="actualVehiclePlate">
          <el-input v-model="form.actualVehiclePlate" placeholder="请输入车牌号" />
        </el-form-item> -->
        <el-form-item label="所属车辆" prop="vehicleId">
          <el-select v-model="form.vehicleId" placeholder="输入车牌号搜索" filterable remote reserve-keyword
            :remote-method="remoteCarSearch" :loading="carLoading" @change="handleCarSelect">
            <el-option v-for="car in carOptions" :key="car.id" :label="car.licensePlate" :value="car.id" />
          </el-select>
        </el-form-item>

        <!-- 可选：展示车牌号，只读 -->
        <!-- <el-form-item label="车牌号" prop="actualVehiclePlate">
          <el-input v-model="form.actualVehiclePlate" disabled />
        </el-form-item> -->
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维护用户" prop="userId">
          <el-select v-model="form.userId" placeholder="输入用户名或昵称搜索" filterable remote reserve-keyword
            :remote-method="remoteUserSearch" :loading="userLoading" @change="handleUserSelect">
            <el-option v-for="user in userOptions" :key="user.userId" :label="user.nickName + '（' + user.userName + '）'"
              :value="user.userId" />
          </el-select>
        </el-form-item>

        <!-- 可选：单独显示姓名，只读 -->
        <!-- <el-form-item label="维护用户姓名" prop="userName">
          <el-input v-model="form.userName" disabled />
        </el-form-item> -->
        <el-form-item label="维护原因" prop="maintenanceReason">
          <el-input v-model="form.maintenanceReason" placeholder="请输入维护原因" />
        </el-form-item>
        <el-form-item label="维护地点" prop="maintenanceLocation">
          <el-input v-model="form.maintenanceLocation" placeholder="请输入维护地点" />
        </el-form-item>
        <el-form-item label="维护费用" prop="cost">
          <el-input v-model="form.cost" placeholder="请输入维护费用" />
        </el-form-item>
        <el-form-item label="维修发票" prop="invoice">
          <!-- <image-upload v-model="form.file"/> -->
          <el-upload class="upload-demo" :action="'#'" :auto-upload="false" :show-file-list="true"
            :on-change="handleFileChange" :file-list="fileList" :on-remove="handleRemove" :limit="1"
            accept="image/jpeg,image/png" list-type="picture-card">
            <!-- 只允许一张图 -->
            <i class="el-icon-plus" v-if="fileList.length === 0"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecords, getRecords, delRecords, addRecords, updateRecords, listUser, listVehicles } from "@/api/vehicles/records";

export default {
  name: "Records",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维护记录表格数据
      recordsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 维修发票时间范围
      daterangeStartTime: [],
      // 维修发票时间范围
      daterangeEndTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        maintenanceRecordsId: null,
        vehicleId: null,
        actualVehiclePlate: null,
        startTime: null,
        endTime: null,
        userId: null,
        userName: null,
        maintenanceReason: null,
        maintenanceLocation: null,
        cost: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vehicleId: [
          { required: true, message: "车辆ID不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
      },
      fileList: [],           // 显示上传列表
      imageFile: null,        // 真正的文件缓存
      userOptions: [],      // 用户搜索结果
      userLoading: false,   // 用户搜索 loading
      carOptions: [],   // 用户搜索结果
      carLoading: false, // 用户搜索 loading
    };
  },
  created() {
    this.getList();
  },
  methods: {
    remoteCarSearch(query) {
      if (!query) {
        this.carOptions = []
        return
      }
      this.carLoading = true
      listVehicles(query)
      .then(res => {
        this.carOptions = res.rows || []
      })
      .catch(() => {
        this.carOptions = []
      })
      .finally(() => {
        this.carLoading = false
      })
    },

    handleCarSelect(carId) {
      const selectedCar = this.carOptions.find(car => car.id === carId)
      this.form.actualVehiclePlate = selectedCar ? selectedCar.licensePlate : ''
    },
    /**
    * 远程搜索用户
    * @param {String} query 用户在下拉框里输入的关键字
    */
    remoteUserSearch(query) {
      if (!query) {
        this.userOptions = []
        return
      }
      this.userLoading = true
      listUser(query)
        .then(res => {
          // 若依接口返回的列表在 res.rows
          this.userOptions = res.rows || []
        })
        .catch(() => {
          this.userOptions = []
        })
        .finally(() => {
          this.userLoading = false
        })
    },

    /**
     * 用户选中之后，自动把 userName 填入 form
     * @param {Number} userId
     */
    handleUserSelect(userId) {
      const u = this.userOptions.find(u => u.userId === userId)
      this.form.userName = u ? u.nickName : ''
    },
    // 选中图片触发
    handleFileChange(file, fileList) {
      this.imageFile = file.raw;
      this.fileList = fileList;
    },

    // 删除图片
    handleRemove(file, fileList) {
      this.imageFile = null;
      this.fileList = fileList;
    },
    /** 查询维护记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
        this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0];
        this.queryParams.params["endStartTime"] = this.daterangeStartTime[1];
      }
      if (null != this.daterangeEndTime && '' != this.daterangeEndTime) {
        this.queryParams.params["beginEndTime"] = this.daterangeEndTime[0];
        this.queryParams.params["endEndTime"] = this.daterangeEndTime[1];
      }
      listRecords(this.queryParams).then(response => {
        this.recordsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        maintenanceRecordsId: null,
        vehicleId: null,
        actualVehiclePlate: null,
        startTime: null,
        endTime: null,
        userId: null,
        userName: null,
        maintenanceReason: null,
        maintenanceLocation: null,
        cost: null,
        invoice: null,
      };
      this.resetForm("form");
      this.fileList = [];
      this.imageFile = null;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeStartTime = [];
      this.daterangeEndTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维护记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRecords(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改维护记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = new FormData();
          for (let key in this.form) {
            if (this.form[key] !== null && this.form[key] !== undefined) {
              formData.append(key, this.form[key]);
            }
          }
          // 一定要改成和后端 AddRecordsForm 中字段名一致
          if (this.imageFile) {
            formData.append("file", this.imageFile); // 这里的 "file" 是后端期待的字段名
          }
          for (let [key, value] of formData.entries()) {
            console.log(`${key}:`, value);
          }
          if (this.form.id != null) {
            updateRecords(formData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecords(formData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除维护记录编号为"' + ids + '"的数据项？').then(function () {
        return delRecords(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('vehicles/records/export', {
        ...this.queryParams
      }, `records_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
